package work.stackandqueque;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

public class Problem394 {

    public String decodeString(String s) {
        StringBuilder res = new StringBuilder();
        Deque<Integer> stack_multi = new ArrayDeque<>();
        Deque<String> stack_res = new ArrayDeque<>();
        int multi = 0;
        for (Character c : s.toCharArray()) {
            if (c == '[') {
                stack_multi.push(multi);
                stack_res.push(res.toString());
                multi = 0;
                res = new StringBuilder();
            }
            else if (c == ']') {
                StringBuilder tmp = new StringBuilder();
                Integer pop = stack_multi.pop();
                for(int i = 0; i < pop; i++) tmp.append(res);
                res = new StringBuilder(stack_res.pop() + tmp);
            }
            else if(c >= '0' && c <= '9') multi = multi * 10 + Integer.parseInt(c + "");
            else res.append(c);
        }
        return res.toString();

    }


    public static void main(String[] args) {
        Problem394 problem394 = new Problem394();
        String string = problem394.decodeString("ab3[a2[cd]]");
        System.out.println(string);
    }

}
